package api

import (
	"errors"
	"go_iot/apps/base"
	"go_iot/apps/project/entity"
	"go_iot/apps/response"
	"go_iot/pkg/util"

	"github.com/kataras/iris/v12"
)

func InitRouter(iris *iris.Application) {
	v1 := iris.Party("/project")
	{
		v1.Get("/list", getProjectList)
		v1.Delete("/delete", delProject)
		v1.Post("/add", addProject)
	}
}

func addProject(ctx iris.Context) {
	var p entity.Project

	if err := ctx.ReadJSON(&p); err != nil {
		response.JsonError(ctx, err)
		return
	}
	p.AccessKey = util.GetRandStr(10)
	p.UserId = ctx.Value("client").(int)
	if err := base.CreateItem(&p); err != nil {
		response.JsonError(ctx, err)
		return
	}

	response.JsonMsg(ctx, "成功")
}

func getProjectList(ctx iris.Context) {
	name := ctx.URLParam("name")
	user := ctx.Value("client").(int)

	page := ctx.URLParamIntDefault("page", 1)
	pageSize := ctx.URLParamIntDefault("pageSize", 10)
	var p = entity.Project{
		Name:   name,
		UserId: user,
	}
	m := p.SearchMap()
	if m == nil {
		response.JsonError(ctx, errors.New("错误请求"))
		return
	}
	pl, total := base.GetListPage[entity.Project](m, page, pageSize)

	response.JSONPagination(ctx, pl, total)
}

func delProject(ctx iris.Context) {
	id, err := ctx.URLParamInt("id")
	if err != nil {
		response.JsonError(ctx, err)
		return
	}
	err = base.DeleteItem[entity.Project](id)
	if err != nil {
		response.JsonError(ctx, err)
		return
	}
	response.JsonMsg(ctx, "成功")
}
